package com.maslyk.job;

import org.apache.log4j.Logger;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.StatefulJob;
import org.quartz.impl.StdSchedulerFactory;

import com.maslyk.invitation.service.email.OrderProcessingService;

/**
 *
 * @author kris
 */
public final class AutomaticJob implements StatefulJob
{    
	private Logger log = Logger.getLogger(AutomaticJob.class);
	
	/**
     przetwarzanie emaili
     */
    public void emailProcessing() throws Exception
    {
    	log.info("Przetwarzanie emaili z komentarzami start...");
        OrderProcessingService.orderEmailProcess();
    }

	public void execute(JobExecutionContext arg0) throws JobExecutionException
	{
		try 
		{
			emailProcessing();
		}
		catch (Exception e) 
		{
			log.error(e,e);
		}
	}
	
	/**
	 * Metoda inicjalizuje zadanie automatyczne powtarzane co interwal czasu
	 * @param interval odstep pomiedzy wywolaniami metody
	 */
	public static void initializeJob(long interval)
	{
		SchedulerFactory schedFact = new StdSchedulerFactory();

		try 
		{
			Scheduler sched = schedFact.getScheduler();
			sched.start();
			sched.scheduleJob(new JobDetail("InvitationJob", Scheduler.DEFAULT_GROUP, AutomaticJob.class), 
								new SimpleTrigger("InvitationTrigger", Scheduler.DEFAULT_GROUP, SimpleTrigger.REPEAT_INDEFINITELY, interval));
		}
		catch (SchedulerException e) 
		{
			Logger log1 = Logger.getLogger(AutomaticJob.class);
			log1.error(e,e);
		}
	}
	
	public static void stop()
	{
		SchedulerFactory schedFact = new StdSchedulerFactory();
		try 
		{
			Scheduler sched = schedFact.getScheduler();
			sched.shutdown();
		}
		catch (SchedulerException e) 
		{
			Logger log1 = Logger.getLogger(AutomaticJob.class);
			log1.error(e,e);
		}
	}
}
